from django.conf import settings
from django.db import DatabaseError
from django.middleware.common import MiddlewareMixin
from utils.services.ResponseService import ResponseService

from utils.services.InteriorCodeService import InteriorCodeService
from utils.exceptions.CustomParamsException import CustomParamsException
from utils.exceptions.CustomJwtExpiredException import CustomJwtExpiredException


class CustomExceptionHandle(MiddlewareMixin):
    """
    统一异常处理
    :param request: 请求对象
    :param exception: 异常对象
    :return:
    """

    def process_exception(self, request, exception):

        # +----------------------------------------------------------------
        # | debug=True时采用系统异常方便调试
        # +----------------------------------------------------------------
        if settings.DEBUG:
            super()
            return

        # +----------------------------------------------------------------
        # | debug=false采用自定义异常
        # +----------------------------------------------------------------
        if isinstance(exception, CustomParamsException):
            # 参数验证异常处理
            return ResponseService.error(exception.message, exception.insideCode).data()

        if isinstance(exception, CustomJwtExpiredException):
            # token过期异常处理
            return ResponseService.error(exception.message, exception.insideCode).data()

        if isinstance(exception, DatabaseError):
            # 数据库异常
            return ResponseService.error(exception.message, exception.insideCode).data()

        elif isinstance(exception, Exception):
            # 服务器异常处理
            return ResponseService.error("系统内部错误", InteriorCodeService.SYSTEM_ERROR).data()
        return None
